// 生成树形结构的函数
function generateTree() {
	$.ajax({
		"url":"menu/get/menuTree.json",
		"dataType":"json",
		"type":"post",
		"success":function(response){
			var result = response.result
			if(result=="SUCCESS"){
				//显示菜单树
				//1.创建 JSON 对象用于存储对 zTree 所做的设置
				var setting = {
						view: {
							addDiyDom: myAddDiyDom,
							addHoverDom: myAddHoverDom,
							removeHoverDom: myRemoveHoverDom
						},
						data: {
							key: {
								url: "xUrl"//解决点击图标不跳转
							}
						}
				};
				//2.准备生成树形结构的 JSON 数据
				var zNodes = response.data;
				//3.初始化树形结构 
				$.fn.zTree.init($("#treeDemo"),setting,zNodes);
			}
			if(result=="FAILED"){
				layer.msg(response.message);
			}
		}
		
	});
}

//修改图标
function myAddDiyDom(treeId,treeNode){
	//控制台打印
	console.log("treeId="+treeId);
	console.log(treeNode);
	//图标的id格式为：treeDemo_1_ico =>treeNode的tId_ico
	//获取spanID
	var spanId = treeNode.tId+"_ico";
	//修改图标
	$("#"+spanId).removeClass().addClass(treeNode.icon);
}

//在移到节点添加按钮组格式为<span><a><i></i></a><a><i></i></a></span>
//添加到id为treeDemo_1_a => tId_a的a标签后面
function myAddHoverDom(treeId,treeNode){
	//为每一组按钮设置id
	var btnGroupId = treeNode.tId+"_btnGroup";
	
	//解决按钮组多次添加
	if($("#"+btnGroupId).length>0){
		return;
	}
	
	//设置按钮内容
	var btnHTML="";
	// 准备各个按钮的HTML标签
	var addBtn = "<a id='"+treeNode.id+"' class='addBtn btn btn-info dropdown-toggle btn-xs' style='margin-left:10px;padding-top:0px;' href='#' title='添加子节点'>&nbsp;&nbsp;<i class='fa fa-fw fa-plus rbg '></i></a>";
	var removeBtn = "<a id='"+treeNode.id+"' class='removeBtn btn btn-info dropdown-toggle btn-xs' style='margin-left:10px;padding-top:0px;' href='#' title='删除节点'>&nbsp;&nbsp;<i class='fa fa-fw fa-times rbg '></i></a>";
	var editBtn = "<a id='"+treeNode.id+"' class='editBtn btn btn-info dropdown-toggle btn-xs' style='margin-left:10px;padding-top:0px;' href='#' title='修改节点'>&nbsp;&nbsp;<i class='fa fa-fw fa-edit rbg '></i></a>";
	
	//根据节点的level来设置相应的按钮
	//获取节点的level
	var level = treeNode.level;
	
	//根节点：添加按钮
	if(level==0){
		btnHTML = addBtn;
	}
	//子节点：添加、修改、删除（没有叶子节点）
	if(level==1){
		btnHTML = addBtn+" "+editBtn;
		//获取节点的子节点的长度
		var length = treeNode.children.length;
		if(length==0){
			btnHTML = btnHTML + " "+ removeBtn;
		}
	}
	//叶子节点：添加、修改、删除
	if(level==2){
		btnHTML = addBtn+" "+editBtn +" " + removeBtn;
	}
	//设置按钮组标签
	var aId = treeNode.tId+"_a";
	$("#"+aId).after("<span id='"+btnGroupId+"'>"+btnHTML+"</span>");
}

//在移开节点生成按钮组
function myRemoveHoverDom(treeId,treeNode){
	
	//获取按钮组id
	var btnGroupId = treeNode.tId+"_btnGroup";
	//移除按钮组
	$("#"+btnGroupId).remove();
}

